<template>
  <div class="m-view-newsPush m-window">
    <div class="m-condition">
      <el-form :model="searchForm">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="工厂：" label-width="70px">
              <el-select
                placeholder="请选择工厂"
                v-model="searchForm.factory"
                clearable
              >
                <el-option
                  v-for="(item, index) in factoryItem"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="edit">编辑</el-button>
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="add">新增</el-button>
          </el-col>
          <el-col :span="2" class="m-floatright">
            <el-button type="primary" @click="getMsgSendAccountList"
              >查询</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="m-agTable m-bottom m-applySoleListTable">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        v-loading="loading"
      ></ag-grid-vue>
    </div>
     <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="searchForm.current"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="searchForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchForm.total"
      ></el-pagination>
    </div>
    <!-- 新增/编辑 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="姓名：" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="账号：" prop="sapgh">
          <el-input
            v-model="ruleForm.sapgh"
            placeholder="请输入账号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="state">
          <el-select
            placeholder="请选择状态"
            v-model="ruleForm.state"
            clearable
          >
            <el-option
              v-for="(item, index) in statusItem"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工厂代码：" prop="factory">
          <el-input
            v-model="ruleForm.factory"
            placeholder="请输入工厂代码"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="AddSaveData('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import gridOptions from "lesso-common/public/gridOptions";
import _Api from "@/api";
import constant from "@/public/constant";

export default {
  data() {
    return {
      searchForm: {
        factory: "", //工厂
         size: 30,
        current: 1,
        total:0,
      },
      factoryItem: [], //状态列表
      //ag-grid 配置项
      gridOptions: null,
      columnDefs: null,
      rowData: [], //  表格数据
      loading: false, //加载条
      // 新增
      dialogVisible: false,
      title: "新增",
      ruleForm: {
        name: "",
        sapgh: "",
        state: 1,
        factory: "",
        id: "",
      },

      rules: {
        name: {
          required: true,
          message: "姓名不能为空",
          trigger: "blur",
        },
        sapgh: {
          required: true,
          message: "账号不能为空",
          trigger: "blur",
        },
        state: {
          required: true,
          message: "状态不能为空",
          trigger: "blur,change",
        },
        factory: {
          required: true,
          message: "工厂代码不能为空",
          trigger: "blur",
        },
      },
      statusItem: [
        { code: 0, name: "禁用" },
        { code: 1, name: "启用" },
      ], //状态列表
    };
  },
  beforeMount() {
    this.gridOptions = gridOptions();
    this.columnDefs = [
      {
        headerName: "姓名",
        field: "name",
        checkboxSelection: true,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
      },
      { headerName: "账号", field: "sapgh" },
      { headerName: "状态", field: "state",
         valueFormatter: (params) => {
          for (let i = 0; i < this.statusItem.length; i++) {
            const status = this.statusItem[i];
            if (status.code === params.value) {
              return status.name;
            }
          }
          return params.value;
        },
       },
      { headerName: "工厂代码", field: "factory" },
    ];
  },
  mounted() {
    this.getFactory();
    this.getMsgSendAccountList();
  },
  methods: {
    // 获取推送消息列表
    getMsgSendAccountList() {
      console.log(this.searchForm, "searchForm");
      let params = {
        size: this.searchForm.size,
        current: this.searchForm.current,
        eqParams: { factory: this.searchForm.factory }, //精确查询
        likeParams: {}, //模糊查询
      };
      this.loading = true;
      _Api
        .getMsgSendAccount(params)
        .then((response) => {
          let data = response.data;
          this.searchForm.total = data.total;
          if (data.code == 1 && data.total != 0) {
            this.rowData = data.rows;
            this.loading = false;
          } else {
            this.loading = false;
            this.rowData = [];
          }
        })
        .catch((err) => {
          this.rowData = [];
          this.loading = false;
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 获取工厂
    getFactory() {
      let params = {
        type: 2,
      };
      _Api
        .getFactory(params)
        .then((response) => {
          console.log(response, "获取工厂");
          let data = response.data;
          if (data.code == 1 && data.total != 0) {
            let dataArr = data.rows;
            //  factoryItem
            dataArr.forEach((item) => {
              let obj = {};
              obj.code = item.factory;
              obj.name = item.name;
              this.factoryItem.push(obj);
            });
          } else {
            this.factoryItem = [];
            this.$message({
              message: data.msg,
              type: "warning",
            });
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 新增
    add() {
      this.dialogVisible = true;
    },
    // 编辑
    edit() {
      let rows = this.gridOptions.api.getSelectedRows();

      this.dialogVisible = true;
      this.ruleForm.name = rows[0].name;
      this.ruleForm.sapgh = rows[0].sapgh;
      this.ruleForm.state = rows[0].state;
      this.ruleForm.factory = rows[0].factory;
      this.ruleForm.id = rows[0].id;
    },
    // 保存
    AddSaveData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            //编辑
            let parmas = {
              name: this.ruleForm.name,
              sapgh: this.ruleForm.sapgh,
              state: this.ruleForm.state,
              factory: this.ruleForm.factory,
              id:this.ruleForm.id,
              modifyer: constant.user.loginName, //登录人名称
              modifyerId: constant.user.id, //登录人Id
              modifyDate: this.curentTime(), //获取当前时间
            };
            _Api
              .editNewsPush(parmas)
              .then((response) => {
                let data = response.data;
                if (data.code == 1) {
                  this.$message({
                    message: data.msg,
                    type: "success",
                  });
                  this.getMsgSendAccountList();
                  this.dialogVisible = false;
                } else {
                  this.$message({
                    message: data.msg,
                    type: "warning",
                  });
                  // this.dialogVisible = false;
                }
              })
              .catch((err) => {
                this.$alert(err.data.message, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              });
          } else {
            //添加
            let parmas = {
              name: this.ruleForm.name,
              sapgh: this.ruleForm.sapgh,
              state: this.ruleForm.state,
              factory: this.ruleForm.factory,
              creator: constant.user.loginName, //登录人名称
              creatorId: constant.user.id, //登录人Id
              createDate: this.curentTime(), //获取当前时间
            };
            _Api
              .addNewsPush(parmas)
              .then((response) => {
                let data = response.data;
                if (data.code == 1) {
                  this.$message({
                    message: data.msg,
                    type: "success",
                  });
                  this.getMsgSendAccountList();
                  this.dialogVisible = false;
                } else {
                  this.$message({
                    message: data.msg,
                    type: "warning",
                  });
                  // this.dialogVisible = false;
                }
              })
              .catch((err) => {
                this.$alert(err.data.message, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.ruleForm.name = "";
      this.ruleForm.sapgh = "";
      this.ruleForm.state = 1;
      this.ruleForm.factory = "";
      this.ruleForm.id = "";
    },
    // 获取当前日期时间
    curentTime() {
      var now = new Date();

      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日

      var hh = now.getHours(); //时
      var mm = now.getMinutes(); //分
      var ss = now.getSeconds(); //分

      var clock = year + "-";

      if (month < 10) clock += "0";

      clock += month + "-";

      if (day < 10) clock += "0";

      clock += day + " ";

      if (hh < 10) clock += "0";

      clock += hh + ":";
      if (mm < 10) clock += "0";
      clock += mm + ":";

      if (ss < 10) clock += "0";
      clock += ss;
      return clock;
    },
      // 每页显示条数改变回调
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.getMsgSendAccountList();
    },
    // 页码改变回调
    handleCurrentChange(val) {
      this.searchForm.current = val;
      this.getMsgSendAccountList();
    },
    // 点击上一页回调
    handlePrevClick(val) {
      this.searchForm.current = val;
    },
    // 点击下一页回调
    handleNextClick(val) {
      this.searchForm.current = val;
    },
  },
};
</script>